import styles from './popup.module.css'

interface Ipopup {
  width?: string;
  height?: string;
  title?: string;
  pos?: string;
  mask?: boolean;
  confirmText?: string;
  cancelText?: string;
  content?: string;
  confirm:()=>void
}

interface Icomponent {
  tempContainer: HTMLElement;
  init: () => void;
  template: () => void;
  handle: () => void;
}

function popup(options: Ipopup) {
  return new Popup(options)
}

class Popup implements Icomponent {
  tempContainer = document.createElement('div');
  mask = document.createElement('div');

  constructor(private settings: Ipopup) {
    this.settings = Object.assign({
      width: '520',
      height: '520',
      title: '提示',
      pos: 'center',
      mask: true,
      confirmText: '确定',
      cancelText: '取消',
      content: '这是一条提示消息',
      confirm:()=>{}
    }, this.settings)
    this.init()
  }
  // 初始化
  init() {
    this.settings.mask && this.createMask();
    this.template();
    this.handle();
    // this.createCallback();
  }

  // 创建模板
  template() {
    this.tempContainer.className = styles.modalBox;
    this.tempContainer.innerHTML =
      `
         <view class="${styles.modalTop}">
          <text class="${styles.modalTitle}">${this.settings.title}</text>
          <view class="${styles.modalContent}">${this.settings.content}</view>
        </view>
        <view class="${styles.modalBtn}">
            <view id="cancleBtn" class="${styles.item}" @click="cancel">${this.settings.cancelText}</view>
            <text class="${styles.line}" color="#eee"></text>
            <view id="confirmBtn" class="${styles.active} ${styles.item}" @click="confirm">${this.settings.confirmText}</view>
        </view>
        `;
    document.body.appendChild(this.tempContainer);

  }

  // 事件操作
  handle() {
    // this.mask.addEventListener('click', () => {
    //   document.body.removeChild(this.tempContainer);
    //   this.settings.mask && document.body.removeChild(this.mask)
    // })
    const cancleBtn = document.getElementById('cancleBtn');
    cancleBtn.addEventListener('click', () => {
      document.body.removeChild(this.tempContainer);
      this.settings.mask && document.body.removeChild(this.mask)
    })
    const confirmBtn = document.getElementById('confirmBtn');
    confirmBtn.addEventListener('click', () => {
      document.body.removeChild(this.tempContainer);
      this.settings.mask && document.body.removeChild(this.mask)
      this.settings.confirm && this.settings.confirm()
    })
  }

  createCallback() {
    const popupContent = this.tempContainer.querySelector(`.${styles.content}`);
    this.settings.content && this.settings.content(popupContent)

  }

  createMask() {
    this.mask = document.createElement('div');
    this.mask.className = styles.mask;
    document.body.appendChild(this.mask);
  }

}

export default popup;
